package com.google.adwords.samples.convert;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * The AdWords API will only output reports in XML, as of V10. This utility will
 * convert an XML report into a CSV report.
 * 
 * TODO: Validate input files
 * @author alecmgo@gmail.com (Alec Go)
 * 
 */
public class XmlToCsvConverter {
  final static Logger logger =
      Logger.getLogger(XmlToCsvConverter.class.getName());
  
  final private DefaultHandler handler;
  final private SAXParser saxParser;
  public static String currentAccount = "";
  
  /**
   * Command-line entrypoint. 
   */
  public static void main(String[] args) throws Exception{
    File dir = new File(args[0]);
    XmlToCsvConverter x = new XmlToCsvConverter(dir);
    x.processDirectory(dir);
  }
  
  /**
   * Constructor - initializes the SAX Parser
   * @throws SAXException
   * @throws ParserConfigurationException
   */
  public XmlToCsvConverter(File dir) throws SAXException,
      ParserConfigurationException, IOException {
    handler = new ReportXmlHandler(dir);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    saxParser = factory.newSAXParser();
  }

  /**
   * Processes directory
   * @param dir
   */
  public void processDirectory(File dir) throws IOException, SAXException{
    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i = 0; i < children.length; i++) {
        processDirectory(new File(dir, children[i]));
      }
    } else {      
      processFile(dir);
    }
  }
  
  /**
   * Processes file
   * @param file
   * @throws IOException
   * @throws SAXException
   */
  public void processFile(File file) throws IOException, SAXException {
    if((file.getName().indexOf("keywords.xml") != -1) && (file.getName().endsWith("xml"))) {
      logger.info("Processing: " + file.getAbsoluteFile());
      XmlToCsvConverter.currentAccount = file.getName().replace("-keywords.xml", "");
      saxParser.parse(file, handler);
    }
  }
}